package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.SaleBean;
import com.project.bean.SaleCartBean;
import com.project.bean.SaleDetailBean;
import com.project.mapper.IProductMapper;
import com.project.mapper.ISaleCartMapper;
import com.project.mapper.ISaleDetailMapper;
import com.project.mapper.ISaleMapper;
import com.project.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class SaleServiceImp implements ISaleService {
    @Autowired
    private ISaleCartMapper saleCartMapper;
    @Autowired
    private ISaleMapper saleMapper;
    @Autowired
    private ISaleDetailMapper saleDetailMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public void add(SaleBean sale, Integer userId) {
        //查询销售总额
        Integer total = saleCartMapper.getTotalByUser(userId);
        sale.setTotal(total);
        //添加销售订单
        saleMapper.insert(sale);
        //查询销售车集合
        List<SaleCartBean> saleCartList = saleCartMapper.findByUserId(userId);
        //批量添加销售明细,同时更新库存中的商品数量
        saleDetailMapper.addBySaleCartList(sale.getId(), saleCartList);
        productMapper.updateBySaleCartList(saleCartList);
        //清空销售车
        QueryWrapper<SaleCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        saleCartMapper.delete(qw);
    }

    @Override
    public IPage<SaleBean> cutByItem(Integer pageNO, String client, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<SaleBean> qw = new QueryWrapper<>();
        if (client != null && !"".equals(client)){
            qw.like("s_client",client);
        }
        if (startDate!=null){
            qw.ge("s_date",startDate);
        }
        if (endDate!=null){
            qw.le("s_date",endDate);
        }
            return saleMapper.selectPage(new Page<>(pageNO,5),qw);
    }

    @Override
    public SaleBean findById(Integer id) {

        SaleBean sale = saleMapper.selectById(id);
        List<SaleDetailBean> saleDetailList = saleDetailMapper.findBySale(id);
        sale.setSaleDetailList(saleDetailList);

        return sale;
    }

    @Override
    public Integer getTotalByUser(Integer userId) {
      return  saleCartMapper.getTotalByUser(userId);
    }
}
